<template>
  <div class="cate-list">
    <div class="left">
      <van-sidebar v-model="active" @change="onChange">
        <van-sidebar-item v-for="item in cate" :key="item.id" :title="item.name" />
      </van-sidebar>
    </div>
    <div class="right">
      <!-- 上方搜索选项 -->
      <div class="right-search">
        <div 
            class="right-search-item" 
            :class="{ active: item === 'com' }" 
            @click="selectList('com')"
        >
          综合
        </div>
        <div
          class="right-search-item"
          :class="{ active: item === 'count' }"
          @click="selectList('count')"
        >
          销量
        </div>
        <div class="right-search-item">
          <span :class="{ active: item.includes('price') }" @click="selectList('priceAsc')">价格</span>
          <van-icon
            name="arrow-up"
            :class="{ active: item === 'priceAsc' }"
            @click="selectList('priceAsc')"
          />
          <van-icon
            name="arrow-down"
            :class="{ active: item === 'priceDesc' }"
            @click="selectList('priceDesc')"
          />
        </div>
        <div
          class="right-search-item"
          :class="{ active: item === 'stock' }"
          @click="selectList('stock')"
        >
          仅看有货
        </div>
      </div>
      <!-- 下方商品列表,支持无限滚动和索引滚动 -->
      <div
        class="cate-list-container"
        @scroll="isLeftClick ? null : scroll()"
        @wheel="isLeftClick = false"
        @mousedown="isLeftClick = false"
        @mouseup="isLeftClick = false"
      >
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <section class="cate-list-item" v-for="item in cate" :key="item.id">
            <div class="cate-list-title" :id="item.id">{{ item.name }}</div>
            <div
              v-for="product in list1?.filter((item1) => item1.cateid == item.id)"
              :key="product._id"
              class="product-item"
              @click="goDetails(product._id)"
            >
              <div class="product-img">
                <img :src="product.img" alt="" />
              </div>
              <div class="product-info">
                <div class="product-name">{{ product.name }}</div>
                <div class="product-oldPrice">{{ product.oldPrice.toFixed(2) }}</div>
                <div class="product-newPrice">￥{{ product.newPrice.toFixed(2) }}</div>
                <div class="product-addCart">
                  <van-icon
                    name="shopping-cart-o"
                    color="#ee0a24"
                    @click.stop="addCart(product._id)"
                    size="20"
                  ></van-icon>
                </div>
              </div>
            </div>
          </section>
        </van-list>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router';

const router = useRouter()


interface cateItem {
  id: string
  name: string
}
type catelist = cateItem[]
const { cate, list } = defineProps({
  cate: {
    type: Array as () => catelist, // 类型
    default: () => []
  },
  list: Array
})
const active = ref(localStorage.getItem('active')?JSON.parse(localStorage.getItem('active')):0)

//判断是否是左侧点击导致的滚动还是右侧自身的滚动
const isLeftClick = ref(true)
//判断是鼠标带动列表滚动还是右侧自身滚动
//根据列表元素上的wheel事件和mousedown事件触发

// 点击左侧菜单,切换右侧列表
const onChange = (index: any) => {
  active.value = index
  isLeftClick.value = true
  const index1 = cate[index].id
  //滚动到指定位置
  const element = document.getElementById(index1)
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' })
  }
}
//防抖函数
const debounce = (fn: any, delay: number) => {
  let timer: any
  return function (...args: any) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

//cate-list-container滚动时,检测其中的cate-list-title是否到顶,到顶切换为对应的index
const scroll = debounce(() => {
  const list1 = document.querySelectorAll('.cate-list-title')
  list1.forEach((item, index) => {
    const top = item.getBoundingClientRect().top - 130 //获取距离顶部的距离
    if (top <= 0) {
      active.value = index
    }
  })
}, 100)

//无限滚动
const list1 = ref(localStorage.getItem('list1')?JSON.parse(localStorage.getItem('list1')):[]);
const loading = ref(localStorage.getItem('loading')?JSON.parse(localStorage.getItem('loading')):true);
const finished = ref(localStorage.getItem('finished')?JSON.parse(localStorage.getItem('finished')):false);
const page = ref(localStorage.getItem('page')?JSON.parse(localStorage.getItem('page')):0);
const pagesize = ref(4);
const total = ref(13);
const onLoad = () => {
    // 异步更新数据
    // setTimeout 仅做示例，真实场景中一般为 ajax 请求
    console.log(222);
    
    setTimeout(() => {
        page.value += 1;
        const newlist = list?.slice((page.value-1 )* pagesize.value, page.value * pagesize.value);
        list1.value = [...list1.value, ...newlist];
        // 加载状态结束
        loading.value = false;
        // 数据全部加载完成
        if (list1.value.length >= total.value) {
          console.log('加载完成');
          
            finished.value = true;
        }
    }, 2000);
};
onMounted(()=>{
  //滚动到滚动列表的相应位置
  const scrollTop = localStorage.getItem('scrollTop')?JSON.parse(localStorage.getItem('scrollTop')):0
  scrollTop? (document.querySelector('.cate-list-container')!.scrollTop = scrollTop):null
  onLoad()
})


//排序选择
const item = ref(localStorage.getItem('item')?localStorage.getItem('item'):'com')
//向父组件传递一个方法
const emit = defineEmits(['sortList','addCart'])
const sortList = (item1: string) => {
  emit('sortList', item1)
}
const selectList = (item1: string) => {
  active.value = 0
  item.value = item1
  list1.value = []
  page.value = 0
  finished.value = false
  loading.value = true
  sortList(item1)
  onLoad()
}


//加入购物车,存储到仓库中
const addCart = (id: number) => {
  const product = list?.find((item) => item._id === id)
  console.log(111);
  
  if (product) {
    console.log(222);
    
    emit('addCart', product)
  }
}
//使用事件修饰符.stop阻止触发父组件的事件,点击购物车时不会跳转详情页

//跳转详情页
const goDetails = (id: number) => {
  router.push({
    name: 'detail',
    params: { id }
  })
}

//组件销毁前保存状态等
onBeforeUnmount(()=>{
    console.log('cate-list组件销毁了')
    //保存状态等
    localStorage.setItem('list1',JSON.stringify(list1.value))
    localStorage.setItem('item',item.value)
    localStorage.setItem('page',page.value.toString())
    localStorage.setItem('pagesize',pagesize.value.toString())
    localStorage.setItem('total',total.value.toString())
    localStorage.setItem('finished',finished.value.toString())
    localStorage.setItem('loading',loading.value.toString())
    localStorage.setItem('active',active.value.toString())
    //记录当前的滚动条位置
    localStorage.setItem('scrollTop',document.querySelector('.cate-list-container')?.scrollTop)
})

</script>

<style lang="scss">
.cate-list {
  width: 100%;
  height: calc(100vh - 150px);
  display: flex;
  border-top: 0.5px solid rgb(230, 230, 230);
  .left {
    width: 20%;
    height: 100%;
    background-color: rgb(247, 247, 247);
  }
  .right {
    height: 100%;
    width: 80%;
    .right-search {
      width: 95%;
      margin: 0 2.5%;
      height: 5%;
      display: flex;
      align-items: center;
      .right-search-item {
        width: 25%;
        height: 100%;
        font-size: 13px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .active {
        color: #07c160;
      }
    }
    .cate-list-container {
      width: 100%;
      height: 95%;
      overflow-y: scroll;
      .cate-list-item {
        width: 90%;
        margin: 10px 5%;
        .cate-list-title {
          width: 100%;
          font-size: 14px;
          font-weight: bold;
          border-left: 4px solid #07c160;
          padding-left: 10px;
          margin-bottom: 20px;
        }
        .product-item {
          width: 100%;
          border-top: 1px solid #ccc;
          padding: 5%;
          display: flex;
          .product-img {
            width: 40%;
            height: 90%;
            img {
              width: 100%;
              height: 100%;
            }
          }
          .product-info {
            width: 60%;
            height: 100%;
            padding: 0 10px;
            position: relative;
            .product-name {
              font-size: 1rem;
              font-weight: bold;
              display: -webkit-box;
              -webkit-line-clamp: 2; /* 控制显示的行数 */
              -webkit-box-orient: vertical;
              overflow: hidden;
              text-overflow: ellipsis;
              word-break: break-all; /* 防止长单词溢出容器 */
            }
            .product-oldPrice {
              text-decoration: line-through;
              color: #ccc;
              margin: 10px 0;
            }
            .product-newPrice {
              //暗红色
              color: rgb(218, 24, 33);
            }
            .product-addCart {
              position: absolute;
              right: 10px;
              bottom: 0px;
            }
          }
        }
      }
    }
  }
}
:root {
  --van-sidebar-selected-text-color: #07c160; // 选中颜色
}
</style>
